//
//  JDLoginViewController.swift
//  DragonWallet
//
//  Created by volantPig on 2024/2/21.
//

import UIKit
import SwiftyJSON

class JDLoginViewController: JDBaseViewController {

//    override func viewWillAppear(_ animated: Bool) {
//        super.viewWillAppear(animated)
//        let popupView = JDPPPopupView()
//        popupView.modalPresentationStyle = .custom
//        popupView.modalTransitionStyle = .crossDissolve
//        self.presentVC(popupView)
//    }
    
    private var inputContainerView: UIView?
    private var middleLine: UIView?
    var phoneInputView: UITextField?
    var passwordInputView: UITextField?
    var areaCodeLabel: UILabel?
    var verticalLine: UIView?
    var sendValidCodeButton: UIButton?
    
    var checkBoxButton: UIButton?
    var privacyPolicyLabel: LinkLabel?
    var ppLabel: UITextView?
    var loginButton: UIButton?
    
    /// 0: 验证码登录  1: 账号密码登录
    var loginType = 0
    var changeLoginTypeButton: UIButton?
    var countDownTimer: Timer?
    var countNumber = 60
    
    var openinstallValue: String = ""
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = .white
        // MARK: 修改【状态栏】和【导航栏】的颜色
        self.navigationController?.navigationBar.backgroundColor = .white
//        self.customStatusBarBackgroundColor(.white)
        self.customNavigationBar?.isHidden = true
        self.customBackItem()
        self.setupUIElements()
        
        OpenInstallSDK.defaultManager()?.getInstallParmsCompleted({ openinstallInfo in
            
            guard let _ = openinstallInfo?.data else { return }
            
            if let openinstallDic = openinstallInfo?.data.first {
                let value = JSON(openinstallDic.value as Any).stringValue
                if value.count > 0 {
                    self.openinstallValue = value
                }
            }
        })
        
        // Do any additional setup after loading the view.
    }
    
    func customBackItem() {
        let backButton = UIButton(type: .custom)
        backButton.setImage(UIImage(named: "black_back")?.withRenderingMode(.alwaysOriginal), for: .normal)
        backButton.frame = CGRectMake(12, statusBarHeight, 50, 44)
        backButton.addTarget(self, action: #selector(backButtonAction), for: .touchUpInside)
        backButton.setTitleColor(.init(hexString: "#868F92"), for: .normal)
        backButton.titleLabel?.font = UIFont.systemFont(ofSize: 14, weight: .regular)
        
        self.view.addSubview(backButton)
//        let barButtonItem = UIBarButtonItem(customView: backButton)
//        self.navigationItem.leftBarButtonItem = barButtonItem
    }
    
    @objc func backButtonAction() {
        self.dismiss(animated: true)
    }
    
    func setupUIElements() {
        
        let logoImgV = UIImageView()
        self.view.addSubview(logoImgV)
        logoImgV.snp.makeConstraints { make in
            make.left.equalTo(self.view).offset(26)
            make.top.equalTo(self.view).offset(79+statusBarHeight)//
//            make.size.equalTo(CGSize(width: 150, height: 55))
            make.size.equalTo(CGSize(width: 115, height: 42))
        }
        logoImgV.image = UIImage(named: "login_logo")?.withRenderingMode(.alwaysOriginal)
        
        self.inputContainerView = UIView()
        self.view.addSubview(self.inputContainerView!)
        self.inputContainerView?.snp.makeConstraints { make in
            make.left.equalTo(self.view).offset(12)
            make.right.equalTo(self.view).offset(-12)
            make.top.equalTo(logoImgV.snp.bottom).offset(27)
            make.height.equalTo(111)
        }
        self.inputContainerView?.layer.cornerRadius = 8
        self.inputContainerView?.layer.borderWidth = 1
        self.inputContainerView?.layer.borderColor = cgColor("#EAEBED")
        self.inputContainerView?.backgroundColor = .white
        
        self.middleLine = UIView()
        self.inputContainerView?.addSubview(self.middleLine!)
        self.middleLine?.snp.makeConstraints { make in
            make.left.equalTo(self.inputContainerView!).offset(15)
            make.right.equalTo(self.inputContainerView!).offset(-15)
            make.centerY.equalTo(self.inputContainerView!)
            make.height.equalTo(1)
        }
        self.middleLine?.backgroundColor = color("#EAEBED")
        
        self.passwordInputView = UITextField()
        self.inputContainerView?.addSubview(self.passwordInputView!)
        self.passwordInputView?.snp.makeConstraints({ make in
            make.left.equalTo(self.inputContainerView!).offset(15)
            make.right.equalTo(self.inputContainerView!).offset(-15)
            make.top.equalTo(self.middleLine!.snp.bottom)
            make.bottom.equalTo(self.inputContainerView!)
        })
        self.passwordInputView?.placeholder = "验证码"
        self.passwordInputView?.font = UIFont.systemFont(ofSize: 14, weight: .regular)
        self.passwordInputView?.textColor = color("#333333")
        
        self.areaCodeLabel = UILabel()
        self.inputContainerView?.addSubview(self.areaCodeLabel!)
        self.areaCodeLabel?.snp.makeConstraints { make in
            make.left.equalTo(self.inputContainerView!).offset(15)
            make.top.equalTo(self.inputContainerView!)
            make.bottom.equalTo(self.middleLine!.snp.top)
        }
        self.areaCodeLabel?.text = "+86"
        self.areaCodeLabel?.textColor = color("#868F92")
        self.areaCodeLabel?.font = UIFont.systemFont(ofSize: 14, weight: .regular)
        
        self.verticalLine = UIView()
        self.inputContainerView?.addSubview(self.verticalLine!)
        self.verticalLine?.snp.makeConstraints { make in
            make.left.equalTo(self.areaCodeLabel!.snp.right).offset(10)
            make.centerY.equalTo(self.areaCodeLabel!)
            make.size.equalTo(CGSize(width: 1, height: 20))
        }
        self.verticalLine?.backgroundColor = color("#EAEBED")
        
        self.sendValidCodeButton = UIButton(type: .custom)
        self.inputContainerView?.addSubview(self.sendValidCodeButton!)
        self.sendValidCodeButton?.snp.makeConstraints({ make in
            make.centerY.equalTo(self.areaCodeLabel!)
            make.right.equalTo(self.inputContainerView!).offset(-15)
        })
        self.sendValidCodeButton?.setTitle("发送验证码", for: .normal)
        self.sendValidCodeButton?.setTitleColor(color("#FA6161"), for: .normal)
        self.sendValidCodeButton?.titleLabel?.font = UIFont.systemFont(ofSize: 14, weight: .regular)
        self.sendValidCodeButton?.addTarget(self, action: #selector(sendValidCodeAction), for: .touchUpInside)
        
        // TODO: 限制一下，只让输入11个数字，不然输入空格
        self.phoneInputView = UITextField()
        self.inputContainerView?.addSubview(self.phoneInputView!)
        self.phoneInputView?.snp.makeConstraints({ make in
            make.left.equalTo(self.inputContainerView!).offset(53+15)
            make.top.equalTo(self.inputContainerView!)
            make.bottom.equalTo(self.middleLine!.snp.top)
            make.right.equalTo(self.inputContainerView!).offset(-90)
        })
        self.phoneInputView?.font = UIFont.systemFont(ofSize: 14, weight: .regular)
        self.phoneInputView?.textColor = color("#333333")
        self.phoneInputView?.placeholder = "手机号"
        
//        var checkBoxButton: UIButton?
//        var ppLabel: UITextView?
//        var loginButton: UIButton?
        
        self.checkBoxButton = UIButton(type: .custom)
        self.view.addSubview(self.checkBoxButton!)
        self.checkBoxButton?.snp.makeConstraints({ make in
            make.left.equalTo(self.inputContainerView!)
            make.top.equalTo(self.inputContainerView!.snp.bottom).offset(13)
            make.size.equalTo(CGSize(width: 16, height: 16))
        })
        self.checkBoxButton?.setImage(UIImage(named: "checkbox_empty")?.withRenderingMode(.alwaysOriginal), for: .normal)
        self.checkBoxButton?.addTarget(self, action: #selector(checkboxAction(_:)), for: .touchUpInside)
        
//        var privacyPolicyLabel: LinkLabel?
        self.privacyPolicyLabel = LinkLabel()
        self.view.addSubview(self.privacyPolicyLabel!)
        self.privacyPolicyLabel?.snp.makeConstraints({ make in
            make.centerY.equalTo(self.checkBoxButton!)
            make.left.equalTo(self.checkBoxButton!.snp.right).offset(10)
            make.right.equalTo(self.view).offset(-100)
        })
        self.privacyPolicyLabel?.selectLinkStringCompeleted = { [weak self] linkStr in
            
            if linkStr == "用户协议" {
                if let callUrl = URL(string: "https://www.xiaolongbaobao.com/yonghuxieyi.html") {
                    UIApplication.shared.open(callUrl, options: [:]) { isSuccess in
                    }
                }
            } else if linkStr == "隐私政策" {
                if let callUrl = URL(string: "https://www.xiaolongbaobao.com/xieyi.html") {
                    UIApplication.shared.open(callUrl, options: [:]) { isSuccess in
                    }
                }
            }
            printLog("点击的超链接:\(linkStr)")
        }
        
        let linkModel1 = LinkLabelModel()
        linkModel1.linkString = "用户协议"
        linkModel1.linkStrAttributes = [NSAttributedString.Key.foregroundColor: color("#FA6161"), .font: UIFont.systemFont(ofSize: 12, weight: .regular) as Any]
        
        
        let linkModel2 = LinkLabelModel()
        linkModel2.linkString = "隐私政策"
        linkModel2.linkStrAttributes = [NSAttributedString.Key.foregroundColor: color("#FA6161"), .font: UIFont.systemFont(ofSize: 12, weight: .regular) as Any]
        
        
        self.privacyPolicyLabel?.configureLinkInfo("登录即表明同意用户协议和隐私政策", [.foregroundColor: color("#9DA1B2"), .font: UIFont.systemFont(ofSize: 12, weight: .regular) as Any ], [linkModel1,linkModel2])
        
//        self.ppLabel = UITextView()
//        self.ppLabel?.isUserInteractionEnabled = false
//        self.ppLabel?.isEditable = false
//        self.view.addSubview(self.ppLabel!)
//        self.ppLabel?.snp.makeConstraints({ make in
//            make.centerY.equalTo(self.checkBoxButton!)
//            make.left.equalTo(self.checkBoxButton!.snp.right).offset(10)
//            make.right.equalTo(self.view).offset(-100)
////            make.height.equalTo(18)
//        })
//        self.ppLabel?.text = "登录即表明同意用户协议和隐私政策"
//        self.ppLabel?.delegate = self
//        self.ppLabel?.backgroundColor = .red
//        self.ppLabel?.textContainerInset = .zero
        
        
        self.loginButton = UIButton(type: .custom)
        self.view.addSubview(self.loginButton!)
        self.loginButton?.snp.makeConstraints({ make in
            make.left.right.equalTo(self.inputContainerView!)
            make.top.equalTo(self.checkBoxButton!.snp.bottom).offset(23)
            make.height.equalTo(54)
        })
        self.loginButton?.backgroundColor = color("#1C1F32")
        self.loginButton?.setTitle("登录 / 注册", for: .normal)
        self.loginButton?.titleLabel?.font = UIFont.systemFont(ofSize: 16, weight: .regular)
        self.loginButton?.setTitleColor(.white, for: .normal)
        self.loginButton?.layer.cornerRadius = 8
        self.loginButton?.addTarget(self, action: #selector(loginAction), for: .touchUpInside)
        
        self.changeLoginTypeButton = UIButton(type: .custom)
        self.view.addSubview(self.changeLoginTypeButton!)
        self.changeLoginTypeButton?.snp.makeConstraints({ make in
            make.right.equalTo(self.loginButton!)
            make.top.equalTo(self.loginButton!.snp.bottom).offset(13)
        })
        self.changeLoginTypeButton?.setTitle("账号登录", for: .normal)
        self.changeLoginTypeButton?.setTitleColor(color("#FA6161"), for: .normal)
        self.changeLoginTypeButton?.titleLabel?.font = UIFont.systemFont(ofSize: 12, weight: .regular)
        self.changeLoginTypeButton?.addTarget(self, action: #selector(changeLoginTypeAction), for: .touchUpInside)
        self.changeLoginTypeButton?.isHidden = true
        
    }
    
    @objc func changeLoginTypeAction() {
        if self.loginType == 0 {
            // 切换后是账号登录
            self.loginType = 1
            self.changeLoginTypeButton?.setTitle("验证码登录", for: .normal)
            self.areaCodeLabel?.isHidden = true
            self.sendValidCodeButton?.isHidden = true
            self.verticalLine?.isHidden = true
            self.phoneInputView?.placeholder = "输入用户名"
            self.passwordInputView?.placeholder = "输入密码"
            self.phoneInputView?.snp.removeConstraints()
            self.phoneInputView?.snp.makeConstraints({ make in
                make.left.equalTo(self.inputContainerView!).offset(15)
                make.top.equalTo(self.inputContainerView!)
                make.bottom.equalTo(self.middleLine!.snp.top)
                make.right.equalTo(self.inputContainerView!).offset(-15)
            })
        } else {
            // 切换后是验证码登录
            self.loginType = 0
            self.changeLoginTypeButton?.setTitle("账号登录", for: .normal)
            self.areaCodeLabel?.isHidden = false
            self.sendValidCodeButton?.isHidden = false
            self.verticalLine?.isHidden = false
            self.phoneInputView?.placeholder = "手机号"
            self.passwordInputView?.placeholder = "验证码"
            self.phoneInputView?.snp.removeConstraints()
            self.phoneInputView?.snp.makeConstraints({ make in
                make.left.equalTo(self.inputContainerView!).offset(53+15)
                make.top.equalTo(self.inputContainerView!)
                make.bottom.equalTo(self.middleLine!.snp.top)
                make.right.equalTo(self.inputContainerView!).offset(-90)
            })
        }
    }
    
    /// 发送验证码
    @objc func sendValidCodeAction() {
        
        if self.countDownTimer != nil {
            return
        }
        
        printLog("发送验证码")

        var params = [String: Any]()
        params["mobile"] = self.phoneInputView?.text
        
       // 获取验证码接口
        JDNetWorkRequest(.getVerificationCode(params)) {[weak self] responseStr in
            printLog("请求完成:\(responseStr)")
//            {"returnCode":"00","returnMsg":"发送验证码成功","body":null}
        
            guard let currentSelf = self else { return }
            self?.countDownTimer = Timer.scheduledTimer(timeInterval: 1, target: currentSelf, selector: #selector(currentSelf.timeCountDown), userInfo: nil, repeats: true)
            self?.countDownTimer?.fire()
            
        } failure: { error in
            printLog("请求错误:\(error)")
        } error: { errorCode in
            printLog("失败code:\(errorCode)")
        }
    }
    
    @objc func timeCountDown() {
        if self.countNumber > 0 {
            self.countNumber -= 1
            self.sendValidCodeButton?.setTitle("(\(self.countNumber)s)", for: .normal)

        } else {
            self.countDownTimer?.invalidate()
            self.countDownTimer = nil
            self.countNumber = 60
            self.sendValidCodeButton?.setTitle("发送验证码", for: .normal)
        }
    }
    
    @objc func loginAction() {
        
        if self.phoneInputView?.text?.count != 11 {
            self.view.toast(message: "手机号码长度有误")
            return
        }
        
        if !(self.checkBoxButton?.isSelected ?? false) {
            self.view.toast(message: "请认真阅读用户协议和隐私政策")
            return
        }
        self.showLoading()
        if self.loginType == 0 {
            printLog("验证码登录")
//            if (self.passwordInputView?.text?.count ?? 0) < 6 {
//                printLog("请输入正确验证码")
//                return
//            }
            var params = [String: Any]()
            
            params["mobile"] = self.phoneInputView?.text
            params["smsCode"] = self.passwordInputView?.text
            params["loginPlatform"] = 1
            
            if self.openinstallValue.count > 0 {
                params["referrerCode"] = self.openinstallValue
            }
                        
            JDNetWorkRequest(.telLogin(params)) { responseStr in
                printLog("请求成功:\(responseStr)")
                self.dismissLoading()
                let commonModel = JDCommonModel.deserialize(from: responseStr, designatedPath: "")
                
                if commonModel?.code == "0" {
                    // 正常系
                    if let loginModel = JDLoginModel.deserialize(from: responseStr, designatedPath: "data") {
                        
                        // 登录成功 停掉计时器
                        self.countDownTimer?.invalidate()
                        self.countDownTimer = nil
                        self.countNumber = 60
                        
                        JDLoginModel.default.refreshData(loginModel)
                        JDLoginModel.default.mobile = self.phoneInputView?.text
                        printLog("当前用户username:\(loginModel.nickname)")
                        UserDefaults.standard.set(responseStr, forKey: "loginInfo")
                        self.dismiss(animated: true)
                        
                        self.getCurrentTabBarController()?.selectedIndex = 0
                        
                        NotificationCenter.default.post(name: Notification.Name("notificationRefresh"), object: nil)
                        NotificationCenter.default.post(name: Notification.Name("LoginRefresh"), object: nil)
                    } else {
                        self.view.toast(message: commonModel?.msg ?? "网络异常")
                    }
                } else if commonModel?.code == "01" {
                    // 错误
                    self.view.toast(message: commonModel?.msg ?? "网络异常")
                } else if commonModel?.code == "02" {
                    // 未登录
                    if let loginModel = JDLoginModel.deserialize(from: responseStr, designatedPath: "data") {
                        JDLoginModel.default.refreshData(loginModel)
                        printLog("当前用户username:\(loginModel.nickname)")
                        UserDefaults.standard.set(responseStr, forKey: "loginInfo")
                        self.dismiss(animated: true)
                    }
                } else {
                    self.view.toast(message: commonModel?.msg ?? "网络异常")
                }
                
                printLog("查看当前状态:\(commonModel?.code)")
                
//                {"returnCode":"02","returnMsg":"用户已登录！","body":{"onlineSign":"0462557df1284d3e9f72d7d3059c0d9a","password":null,"userid":"f6af4e478fb9418fa47a0435ace66c43","registrationId":"121c83f76133f87e5dc","loginDatetime":1708395819793,"username":"lpt13284231780"}}
                
            } failure: { error in
                self.dismissLoading()
                printLog("请求失败\(error)")
            } error: { errorCode in
                self.dismissLoading()
                printLog("错误code:\(errorCode)")
            }
            
        } else {
            printLog("账号登录")
            var params = [String: Any]()

            params["userName"] = self.phoneInputView?.text//self.phoneInputView?.text
            params["password"] = "000000".strMD5()
            params["registrationId"] = UIDevice.current.identifierForVendor?.uuidString
            
            let now = NSDate()
            let timeInterval:TimeInterval = now.timeIntervalSince1970
            let timeStamp = Int(timeInterval)
            let timeStamp13 = timeStamp*1000
            params["timecheck"] = timeStamp13
            params["jundatoken"] = ("junda"+"\(timeStamp13)"+"_adfs").strMD5()
                        
            JDNetWorkRequest(.passwordLogin(params)) { responseStr in
                self.dismissLoading()
                printLog("请求成功:\(responseStr)")
            } failure: { error in
                self.dismissLoading()
                printLog("请求失败:\(error.errorCode)")
            } error: { errorCode in
                self.dismissLoading()
                printLog("错误代码:\(errorCode)")
            }

            
            
            
        }
    }
    
    @objc func checkboxAction(_ button: UIButton) {
        
        if button.isSelected {
            // 选中 切换至  -> 未选中
            button.isSelected = false
            button.setImage(UIImage(named: "checkbox_empty")?.withRenderingMode(.alwaysOriginal), for: .normal)
        } else {
            // 未选中 切换至 -> 已选中
            button.isSelected = true
            button.setImage(UIImage(named: "checkbox_selected")?.withRenderingMode(.alwaysOriginal), for: .normal)
        }
    }
    

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destination.
        // Pass the selected object to the new view controller.
    }
    */
    
}

extension JDLoginViewController: UITextViewDelegate {
    func textView(_ textView: UITextView, shouldInteractWith URL: URL, in characterRange: NSRange, interaction: UITextItemInteraction) -> Bool {
        
        
        return false
    }
}
